#include "circle_List.h"
#include <stdlib.h> 
#include <stdio.h>

LRecord record = {NULL,0}; 

LNode* CreatNode(LNode* pcur,int value){
    pcur = (LNode* )malloc(sizeof(LNode));
    pcur->date = value;
    pcur->next = NULL;
    record.count++; //number++
    return pcur;
}

void Insert_CircleList(LNode** phead, int value, int position){
    LNode* cur = *phead;
    if (*phead == NULL) {//no List member
        if (position == 0){
            *phead = CreatNode(cur,value);
            record.tail = *phead; //init the tail point and let it's next point to the head address
            record.tail->next = *phead;
        }
        else if (position > 0){
            *phead = CreatNode(cur,0);
            record.tail = *phead; //init the tail point and let it's next point to the head address
            record.tail->next = *phead;
            Insert_CircleList(phead, value, position);
        }
    }
    else { //List member exit
        LNode* ptmp = NULL;
        int _count = 1;
        if (position > record.count){
            _count = record.count;
            while (_count < position){
                ptmp = CreatNode(ptmp, 0);
                record.tail->next = ptmp;
                ptmp->next = *phead; 
                record.tail = ptmp;
                _count++;
            }
            ptmp = CreatNode(ptmp, value);
            record.tail->next = ptmp;
            ptmp->next = *phead; 
            record.tail = ptmp;
        }
        else if (position < record.count){ //the total number of node is bigger than position
            while (_count != position){ //find the Node which is located in position of 'position'
                cur = cur->next;
                _count++;
            } 
            ptmp = CreatNode(ptmp, value);
            ptmp->next = cur->next;
            cur->next = ptmp;
        }
        else if (position == record.count){
            ptmp = CreatNode(ptmp, value);
            record.tail->next = ptmp;
            ptmp->next = *phead; 
            record.tail = ptmp;
        }
    }
}

void Listprint(LNode* phead){
    LNode* cur = phead;
    if (phead == NULL)
        return; 
    while (cur != record.tail){
        printf("%d ",cur->date);
        cur = cur->next;
    }
    printf("%d\n",cur->date);
}
